package com.leetcode.LC;

import java.util.HashMap;
import java.util.Map;

public class LC1160_2 {
    public int countCharacters(String[] words, String chars) {

        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < chars.length(); i++) {
            if (map.containsKey(chars.charAt(i))) {
                map.put(chars.charAt(i), map.get(chars.charAt(i)) + 1);
            } else {
                map.put(chars.charAt(i), 1);
            }
        }

        int sum=0;
        for (String word : words) {
            Map<Character, Integer> map1 = new HashMap<>();
            map1.putAll(map);
            if (findWord(word,map1)){//保证每次传入的map都是原map
                sum+=word.length();
            }
        }
        return sum;
    }

    public boolean findWord(String word, Map<Character, Integer> map) {
        for (int i = 0; i < word.length(); i++) {
            if (map.containsKey(word.charAt(i))) {
                map.put(word.charAt(i), map.get(word.charAt(i)) - 1);
                if (map.get(word.charAt(i)) < 0) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }


    public static void main(String[] args) {
        System.out.println(new LC1160_2().countCharacters(new String[]{"cat", "bt", "hat", "tree"}, "atach"));
    }
}
